<template>
  <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      name="fileList"
      :action="$uploadUrl"
      :headers="uploadHeader"
      :on-success="handleUploadSuccess"
      :before-upload="beforeAvatarUpload">
    <img v-if="data.url" :src="data.url" class="upload-img">
    <div v-else >
      <img src="../../../../assets/images/upload.png"/>
    </div>
  </el-upload>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from "vue";
import {getToken} from "../../../../utils/auth";

  const props = defineProps({
    modelValue:{
      type: String
    }
  });

  const data = reactive({
    url: null
  })

const uploadHeader = ref({ Authorization: "Bearer " + getToken() });

watch(() => props.modelValue, (newVal) => {
  data.url = newVal;
}, { immediate: true });

  const emits = defineEmits(['update:modelValue'])

  function handleUploadSuccess(response){
    data.url = response.data[0].url
    emits('update:modelValue', data.url)
  }
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #087DFA;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 89px;
  height: 89px;
  text-align: center;
}
.upload-img {
  width: 89px;
  height: 89px;
  object-fit: contain
}
</style>
